﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;

namespace WpfApp1
{
    public class UniqueProcess
    {
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        public static string Message = "该应用系统已经在运行！";

        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表
            foreach (Process process in processes)
            {
                //Ignore the current process
                if (process.Id != current.Id)
                {
                    //Return the other process instance.
                    return process;
                }
            }
            return null;
        }

        public static void HandleRunningInstance(Process instance)
        {
            MessageBox.Show(Message, "提示信息");
            IntPtr handle = instance.MainWindowHandle;
            //将原进程显示在最前
            SwitchToThisWindow(handle, true);
            Application.Current.Shutdown();
        }
    }
}
